//
//  HomePageNewTableViewController.m
//  PetTown
//
//  Created by lanou3g on 15/5/28.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "HomePageNewTableViewController.h"
#import "DatabaseHandle.h"
@interface HomePageNewTableViewController ()
{
    MBProgressHUD * HUD;
}
@end

@implementation HomePageNewTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.allDataArray = [[NSMutableArray alloc] init];
    _b = 1;
    //下拉刷新
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    //上啦刷新
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    //设置表透视图以及表尾视图的内容
    [self headerView];
    
    //设置title
    self.navigationItem.title = @"详情";
    
    //评论数据解析
    [self Json];
    
    [self collection];
    [self returns];
    
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
//下拉刷新
- (void)headerRereshing{
    
    [self.tableView headerEndRefreshing];
}
//上拉刷新
-(void)footerRereshing{
    _b++;
    [self Json];
    [self.tableView footerEndRefreshing];
}
//设置收藏按钮
- (void)collection{
    UIButton * collectionButton = [UIButton buttonWithType:(UIButtonTypeSystem)];
    collectionButton.frame = CGRectMake(0, 0, 25, 25);
    [collectionButton setBackgroundImage:[UIImage imageNamed:@"CollectNot.png"] forState:UIControlStateNormal];
    [collectionButton addTarget:self action:@selector(clickRightBueeon:) forControlEvents:UIControlEventTouchDown];
    UIBarButtonItem * rightCollectionBu = [[UIBarButtonItem alloc] initWithCustomView:collectionButton];
    self.navigationItem.rightBarButtonItem = rightCollectionBu;
}
//点击收藏按钮
- (void)clickRightBueeon:(UIBarButtonItem *)leftButton{
    DatabaseHandle * handle = [DatabaseHandle shareInstance];
    PersistManager * persistM = [PersistManager shareInstance];
    //取出数据库中数据
    NSData * modelData = [handle selectActivityWithTitle:ModelKey];
    NSData * allData = [handle selectActivityWithTitle:DataKey];

    NSMutableArray * modelArray = [persistM unarchiverObject:modelData forKey:ModelKey];
    NSMutableArray * allArray = [persistM unarchiverObject:allData forKey:DataKey];

    //判断是否已经收藏
    for (HomePage * homeP in modelArray) {
        if ([homeP.ppid isEqualToString:_homePage.ppid]) {
            [self presentViewController:[persistM repetitionCollect] animated:YES completion:nil];
            return ;
        }
    }
    
    NSMutableArray * NewModelArray = nil;
    NSMutableArray * NewAllArray = nil;
    if (modelArray == nil) {
        NewModelArray = [NSMutableArray array];
        NewAllArray = [NSMutableArray array];
    }else{
        NewModelArray = [NSMutableArray arrayWithArray:modelArray];
        NewAllArray = [NSMutableArray arrayWithArray:allArray];
    }
    
    //如未收藏将对象添加到数组
    [NewModelArray addObject:_homePage];
    [NewAllArray addObject:_allData];
    //删除之前数据
    [handle deleteStudentByKey:ModelKey];
    [handle deleteStudentByKey:DataKey];
    //将数组归档
    [handle insertNewActivity:[persistM dataOfArchiverObject:NewModelArray forKey:ModelKey] Key:ModelKey];
    [handle insertNewActivity:[persistM dataOfArchiverObject:NewAllArray forKey:DataKey] Key:DataKey];
    //收藏成功
    [self presentViewController:[persistM collect] animated:YES completion:nil];

}
//设置返回按钮
- (void)returns{
    UIButton * returnBu = [UIButton buttonWithType:(UIButtonTypeSystem)];
    returnBu.frame = CGRectMake(0, 0, 32, 32);
    [returnBu setBackgroundImage:[UIImage imageNamed:@"ReturnPage.png"] forState:UIControlStateNormal];
    [returnBu addTarget:self action:@selector(returnBueeon:) forControlEvents:UIControlEventTouchDown];
    UIBarButtonItem * leftBu = [[UIBarButtonItem alloc] initWithCustomView:returnBu];
    self.navigationItem.leftBarButtonItem = leftBu;
}
//点击返回按钮
- (void)returnBueeon:(UIBarButtonItem *)leftButton{
    [self.navigationController popViewControllerAnimated:YES];
    
}
//设置表透视图以及表尾视图的内容
- (void)headerView{
    CGFloat pic_h = [[UIScreen mainScreen] bounds].size.width * [_homePage.picheight floatValue] / [_homePage.picwidth floatValue];
    //设置表头视图(详情里面最上面的部分)
    UIView * cell_tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, pic_h+150)];
    self.tableView.tableHeaderView = cell_tableHeaderView;
    //设置表尾视图(最后一条了)
    UILabel * cell_tableFootLable = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 40)];
    cell_tableFootLable.text = @"上拉刷新";
    cell_tableFootLable.textAlignment = NSTextAlignmentCenter;
    cell_tableFootLable.layer.borderWidth = 0.5;
    self.tableView.tableFooterView = cell_tableFootLable;
    //设置表头视图内容
    //图片
    UIImage * imm = [UIImage imageNamed:@"place.jpg"];
    UIImageView * header_imageView = [[UIImageView alloc] init];
    [header_imageView sd_setImageWithURL:[NSURL URLWithString:_homePage.photo] placeholderImage:imm];
    header_imageView.frame = CGRectMake(0, 0, cell_tableHeaderView.frame.size.width, pic_h);
    [cell_tableHeaderView addSubview:header_imageView];
    //用户头像
    UIImageView * user_avatarImageView = [[UIImageView alloc] init];
    [user_avatarImageView sd_setImageWithURL:[NSURL URLWithString:_homePage.avatar] placeholderImage:imm];
    user_avatarImageView.frame = CGRectMake(20, pic_h-20, 50, 50);
    user_avatarImageView.backgroundColor = [UIColor purpleColor];
    [cell_tableHeaderView addSubview:user_avatarImageView];
    //昵称
    UILabel * user_disnameLable = [[UILabel alloc] initWithFrame:CGRectMake(90, pic_h, 150, 50)];
    user_disnameLable.text = _homePage.disname;
    [cell_tableHeaderView addSubview:user_disnameLable];
    //发布时间
    UILabel * user_timeLable = [[UILabel alloc] initWithFrame:CGRectMake(cell_tableHeaderView.frame.size.width-100, pic_h, 100, 50)];
    user_timeLable.text = _homePage.time;
    [cell_tableHeaderView addSubview:user_timeLable];
    //描述
    UILabel * user_contentLable = [[UILabel alloc] initWithFrame:CGRectMake(10, pic_h+50, cell_tableHeaderView.frame.size.width-20, 100)];
    user_contentLable.textAlignment = NSTextAlignmentCenter;
    user_contentLable.layer.cornerRadius = 5.0;
    user_contentLable.text = _homePage.photo_des;
    user_contentLable.font = [UIFont systemFontOfSize:14];
    if ([user_contentLable.text isEqual: @""]){
        user_contentLable.text = @"小主人好懒,什么都不写!";
    }
    user_contentLable.numberOfLines = 0;
    user_contentLable.layer.borderWidth = 0.5;
    [cell_tableHeaderView addSubview:user_contentLable];
}
//评论数据解析
- (void)Json{
    HUD = [[MBProgressHUD alloc] initWithView:self.tableView];
    [self.tableView addSubview:HUD];
    HUD.labelText = @"正在加载";
    [HUD show:YES];
    [HUD hide:NO afterDelay:1.0];
    NSString * uu = [NSString stringWithFormat:ChoicenessDetailsAPI,_homePage.ppid,[NSString stringWithFormat:@"%d",_b]];
    NSURL * url = [NSURL URLWithString:uu];
    
    NSURLRequest * request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:60.0];
    
    __weak HomePageNewTableViewController * HPNTVC = self;
    
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data == nil) {
            return ;
        }
        
//        if (HPNTVC.allData != nil) {
//            HPNTVC.diction = [NSJSONSerialization JSONObjectWithData:HPNTVC.allData options:NSJSONReadingMutableContainers error:nil];
//        }else{
//            HPNTVC.diction = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
//        }
        
        
        HPNTVC.allData = data;
        HPNTVC.diction = [NSJSONSerialization JSONObjectWithData:HPNTVC.allData options:NSJSONReadingMutableContainers error:nil];
        
        NSMutableDictionary * dic = HPNTVC.diction[@"data"];
        NSArray * array = dic[@"list"];
        for (NSDictionary * modelDic in array) {
            Reviewer * reviewer = [[Reviewer alloc] init];
            [reviewer setValuesForKeysWithDictionary:modelDic];
            [HPNTVC.allDataArray addObject:reviewer];
        }
        [self.tableView reloadData];
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    //清除缓存
    SDImageCache * sdI = [SDImageCache sharedImageCache];
    [sdI clearDisk];
    [sdI clearMemory];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return _allDataArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ChoicenessDetailsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"homePageNewCell"];
    if (!cell) {
        cell = [[ChoicenessDetailsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"homePageNewCell"];
    }
    Reviewer * rr = _allDataArray[indexPath.row];
    cell.reviewer = rr;
    //HUD = nil;
    
    // Configure the cell...
    
    return cell;
}
//设置cell高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
